<template>
<!--  <div class="app-container">-->
  <el-dialog :title="title" :visible.sync="visible" width="1300px" append-to-body  >
    <el-form ref="goodsInventoryAddForm" :model="goodsInventoryAddForm" :rules="goodsInventoryAddFormRule"
             label-width="80px" >
<!--      <h3 style="width: 100%;">盘点信息</h3>-->
      <el-row>
        <el-col :span="8">
          <el-form-item label="盘点编号" prop="sn">
            <el-input v-model="goodsInventoryAddForm.sn" disabled ></el-input>
          </el-form-item>

        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点时间" prop="inventory_time">
            <el-date-picker  v-model="goodsInventoryAddForm.inventoryTime" value-format="yyyy-MM-dd" type="date" style="width: 100%"
                             disabled   placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点人" prop="inventoryPerson">
            <el-input v-model="goodsInventoryAddForm.inventoryPerson" placeholder="请选择盘点人" disabled>
<!--              <el-button slot="append" @click="handleUserSelect" icon="el-icon-search"  v-if="!disabled"></el-button>-->
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="盘点范围" prop="inventoryRange"  >
              <el-input v-model="goodsInventoryAddForm.inventoryRange" disabled ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点方法" prop="inventoryMethod"  >
            <el-input v-model="goodsInventoryAddForm.inventoryMethod" disabled ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点类型" prop="inventoryType" >
            <el-input v-model="goodsInventoryAddForm.inventoryType" :disabled="true" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="盘点状态" prop="status">
            <!--            <el-input v-model="goodsInventoryAddForm.status" disabled></el-input>-->
            <el-select v-model="goodsInventoryAddForm.status" placeholder="请选择盘点状态" disabled clearable>
              <el-option label="未盘点" value="0"></el-option>
              <el-option label="盘点中" value="1"></el-option>
              <el-option label="已提交" value="2"></el-option>
              <el-option label="已处理" value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row v-if="goodsInventoryAddForm.inventoryRange =='物料分类'">
        <el-col :span="24">
          <el-form-item label="物料分类" prop="itemTypeNameRange"  >
            <el-input v-model="goodsInventoryAddForm.itemTypeNameRange" disabled ></el-input>
          </el-form-item>

        </el-col>
      </el-row>
      <el-row  v-if="goodsInventoryAddForm.inventoryRange =='仓库'">
        <el-col :span="8">
          <el-form-item label="仓库" prop="warehouseId">
            <el-input v-model="goodsInventoryAddForm.warehouseName" disabled ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库区" prop="locationName">
            <el-input v-model="goodsInventoryAddForm.locationName" disabled ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库位" prop="areaName">
            <el-input v-model="goodsInventoryAddForm.areaName" disabled ></el-input>
          </el-form-item>
        </el-col>
<!--        <el-col :span="8">
          <el-form-item label="仓库" prop="warehouseId">
            <el-cascader v-model="warehouseInfo"  ref="selectck"
                         :options="warehouseOptions"
                         :props="warehouseProps"
                         :style="{width: '100%'}"
                         @change="handleWarehouseChanged"
                         :disabled="disabled"
            >
            </el-cascader>
          </el-form-item>
        </el-col>-->

      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="inventoryDesc">
            <el-input v-model="goodsInventoryAddForm.inventoryDesc" disabled type="textarea" placeholder="请输入备注"  maxlength="250"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="center">盘点清单</el-divider>
      <el-card shadow="always" class="box-card">
        <el-row :gutter="10" class="mb8" v-if="optType =='edit'">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAddProduct"
              v-hasPermi="['mes:wm:pandian:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDeleteProduct"
              v-hasPermi="['mes:wm:pandian:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">

          </el-col>
        </el-row>
          <el-table :data="goodsInventoryAddForm.productList" @selection-change="handleSelectionChange" height="600px">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号"
              type="index"
              width="50">
            </el-table-column>
            <el-table-column label="商品编号1" align="center" prop="itemCode"></el-table-column>
            <el-table-column label="商品名称" align="center" prop="itemName"></el-table-column>
            <el-table-column label="规格型号" align="center" prop="specification" width="80"></el-table-column>
            <el-table-column label="批次号" align="center" prop="batchCode"></el-table-column>
            <el-table-column label="仓库" align="center" prop="warehouseName"></el-table-column>
            <el-table-column label="库区" align="center" prop="locationName"></el-table-column>
            <el-table-column label="库位" align="center" prop="areaName" width="90"></el-table-column>
            <el-table-column
              v-for="col in columnsConfig"
              :key="col.prop"
              :label="col.label"
              :prop="col.prop"
              :width="col.width"
              :align="col.align"
              v-if="col.show">
            </el-table-column>
            <el-table-column label="单位（主）" align="center" prop="unitOfMeasure" width="80" fixed="right"></el-table-column>
            <el-table-column label="库存数量（主）" align="center" prop="quantityOnhand" fixed="right" width="85"></el-table-column>
            <el-table-column label="盘点数量（主）" align="left" prop="inventoryNum" fixed="right" width="130">
              <template slot-scope="scope">
                <el-input-number :min="0" :max="99999999999" :disabled="disabled" size="mini" style="width:100px" v-model="scope.row.inventoryNum"  @change="handleEdit(scope.$index, scope.row)"/>
              </template>
            </el-table-column>
            <el-table-column label="差异（主）" align="center" prop="diffNum" fixed="right" width="130">
              <!--              <template slot-scope="scope">
              &lt;!&ndash;                {{ scope.row.inventory_num - scope.row.remain_num || 0 }}&ndash;&gt;
                                <el-input  v-model="scope.row.diffNum" placeholder="差异" size="mini" style="width:100px" readonly="readonly"></el-input>
                            </template>-->
            </el-table-column>
            <el-table-column label="单位（辅）" align="center" prop="storageUnit"  fixed="right" />
            <el-table-column label="库存数量（辅）" align="center" prop="storageUnitquantity" fixed="right"/>
            <el-table-column label="盘点数量（辅）" align="left" prop="storageInventoryNum" fixed="right" width="130">
              <template slot-scope="scope">
                <el-input-number :min="0" :max="99999999999" :disabled="optType == 'edit' && scope.row.enableMultiUnit == 'Y'? false:true" size="mini" style="width:100px"
                                 v-model="scope.row.storageInventoryNum"  @change="handleFuEdit(scope.$index, scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="差异（辅）" align="center" prop="storageDiffNum" fixed="right"/>
<!--            :disabled="type === 'detail' || type === 'audit'"-->


<!--            <el-table-column label="分类名称" align="center" prop="itemTypeName">
              <template slot-scope="scope">
                {{ scope.row.itemTypeName }}
              </template>
            </el-table-column>-->
            <el-table-column label="备注" align="center" prop="remark" fixed="right" width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" :disabled="disabled"></el-input>

              </template>
            </el-table-column>
<!--            @click="goodsInventoryAddForm.productList.splice(scope.$index, 1)"-->
<!--            <el-table-column label="操作"  fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" type="danger"
                           @click="deleteProduct(scope.$index,scope.row)">删除</el-button>
              </template>
            </el-table-column>-->
          </el-table>
<!--          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getCKItemList"
          />-->
<!--        </el-form-item>-->
<!--      </div>-->
      </el-card>
    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
      <el-button type="primary" @click="submitGoodsInventoryAddForm" v-if="optType=='edit'">保 存</el-button>
      <el-button type="primary" @click="submitTijiao" v-if="optType =='tijiao'">提交确认</el-button>
      <el-button type="primary" @click="cancel">返 回</el-button>
    </div>
    <el-dialog title="新增盘点物料" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" >
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="请选择入库物料" >
                <el-button slot="append" @click="handleSelectStock" icon="el-icon-search" ></el-button>
              </el-input>
            </el-form-item>
            <ItemSelect ref="itemSelect"  @onSelected="onItemSelected" :item-type-id-range="itemTypeIdRange"></ItemSelect>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="itemName">
              <el-input v-model="form.itemName" readonly="readonly" placeholder="请选择入库物料"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchCode">
              <el-input v-model="form.batchCode"  placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" readonly="readonly" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位（主）" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" readonly="readonly" placeholder="请输入单位"  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点数量（主）" prop="inventoryNum">
              <el-input-number :min="0" v-model="form.inventoryNum" @change="handleChangeZhu" placeholder="盘点数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.enableMultiUnit == 'Y'">
          <el-col :span="12">
            <el-form-item label="单位（辅）" prop="storageUnit">
              <el-input v-model="form.storageUnit" readonly="readonly" placeholder="请输入单位（辅）"  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点数量（辅）" prop="storageInventoryNum" >
              <el-input-number :min="0" v-model="form.storageInventoryNum" @change="handleChangeFu"  placeholder="盘点数量（辅）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.enableMultiUnit == 'Y'">
          <el-col :span="8">
            <el-form-item label="换算方式" prop="storageUnitType">
              <el-input :value="form.storageUnitType === 'fixed' ? '固定' : '浮动'"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="换算比例" prop="storageRatio">
              <el-input-number
                :min="0"
                v-model="form.storageRatio"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row  v-if="goodsInventoryAddForm.inventoryRange =='仓库'">
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouseName">
              <el-input v-model="form.warehouseName" disabled ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库区" prop="locationName">
              <el-input v-model="form.locationName" disabled ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库位" prop="areaName">
              <el-input v-model="form.areaName" disabled ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="goodsInventoryAddForm.inventoryRange =='物料分类'">
          <el-col :span="16">
                   <el-form-item label="接收仓库" prop="warehouseId" :disabled="isflckDisabled">
                     <el-cascader v-model="warehouseInfo" ref="selectck"
                                  :options="warehouseOptions"
                                  :props="warehouseProps"
                                  style="width:100%"
                                  @change="handleWarehouseChanged"
                     >
                     </el-cascader>
                   </el-form-item>
                 </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"  />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDialogForm">确 定</el-button>
        <el-button @click="cancelDialog">取 消</el-button>
      </div>
    </el-dialog>


    <UserSingleSelect ref="userSelect" @onSelected="onUserSelected"></UserSingleSelect>
  </el-dialog>
</template>

<script>

import {getTreeList} from "@/api/mes/wm/warehouse";
import ItemSelect from "@/views/mes/wm/pandian/single.vue";
import {addPandian, delPandian, getPandian, updatePandian, updatePandianStatus} from "@/api/mes/wm/pandian";
import UserSingleSelect from "@/components/userSelect/single.vue"
import {genCode} from "@/api/system/autocode/rule";
import {getProductByPId,delPandianproduct,addPandianproduct} from "@/api/mes/wm/pandianproduct";
import {getListWmstock} from "@/api/mes/wm/wmstock";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: 'goodsInventoryAdd',
  components: {Treeselect, UserSingleSelect, ItemSelect},
  props:{
    title:'',
    optType: null,
  },
  data() {
    return {
      itemTypeIdRange:[],
      isflckDisabled:false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      columnsConfig:[],
      warehouseList:[],
      locationList:[],
      areaList:[],
      itemName:'',
      buttonIsShow:false,
      total: 0,
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
        itemCode: undefined,
        itemName: undefined,
        itemTypeId: 0
      },
      visible:false,
      disabled:true,
      //自动生成编码
      autoGenFlag:false,
      warehouseInfo:[],
      zujFlag:false,
      warehouseOptions:[],
      warehouseProps:{
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      // 是否显示弹出层
      open: false,
      form:{},
      adminList: [],
      dialogVisible: false,
      // warehouseList: [],
      deptList: [],
      deptListAll: [],
      id: '',
      type: '',
      /** 出库单表单*/
      goodsInventoryAddForm: {
        productList: []
      },
      /** 校验规则 */
      goodsInventoryAddFormRule: {
        // inventory_person_id: { required: true, message: '请选择盘点人', trigger: 'change' },
        // warehouseInfo: { required: true, message: '请选择报仓库', trigger: 'change' },

      },
      warehouseProduct: null,
      // 表单校验
      rules: {
        itemCode: [
          {required: true, message: "物料不能为空", trigger: "blur"}
        ],
        warehouseId: [
          {required: true, message: "接收仓库不能为空", trigger: "blur"}
        ],
        batchCode: [
          {required: true, message: "批次号不能为空", trigger: "blur"}
        ]
        ,inventoryNum: [
          {required: true, message: "盘点数量不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {

  },
  methods: {
    init(id){
      if(this.optType == 'edit'){
        this.disabled=false
      }
      if(this.optType == 'tijiao'){
        this.disabled=true
      }
      this.itemTypeIdRange=[]
      console.log("editttttt",this.itemTypeIdRange)
      this.warehouseInfo=[]
      this.visible=true
      this.goodsInventoryAddForm.id  = id;
      this.getList(id)
      this.getItemBase()
    },
    getItemBase() {
      getColumnsConfigKey('MdItem_Base').then(res => {
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    handleChangeZhu(value){
      console.log("dddd",value)
      console.log("dddd",this.form.enableMultiUnit)
      //这个数量无论是否开启多单位，多会更改主单位的盘点数量的，所以增加最外层if 只有多单位才计算
      if('Y' == this.form.enableMultiUnit){
        if (this.form.storageUnitType === 'fixed') {
          // 库存单位数量=主数量 / 换算比例
          this.form.storageInventoryNum = parseFloat(
            (this.form.inventoryNum / this.form.storageRatio).toFixed(7)
          );
        }
        //浮动换算就得 填写两个数量计算出浮动率就可以了
        if (this.form.storageUnitType === 'float') {
          this.handleFloatCalculate()
        }
      }

    },
    handleFloatCalculate(triggerSource) {
      //浮动就根据两个数量计算出浮动率就可以了
      if (this.form.storageUnitType !== 'float') return;

      if (this.form.inventoryNum > 0 && this.form.storageInventoryNum > 0) {
        console.log("mmmmmmmmmmmm")
        // 计算新换算比例 = 主数量 / 库存单位数量
        this.form.storageRatio = parseFloat(
          (this.form.inventoryNum / this.form.storageInventoryNum).toFixed(4)
        );
      }
    },
    handleChangeFu(){
      //库存单位显示并且改变了 肯定是启用了多单位  这个if('Y' == this.form.enableMultiUnit)可以省略不写
      if('Y' == this.form.enableMultiUnit) {
        if (this.form.storageUnitType === 'fixed') {
          // 主数量 = 库存单位数量 * 换算比例
          this.form.inventoryNum = parseFloat(
            (this.form.storageInventoryNum * this.form.storageRatio).toFixed(7)
          );
        }
        //浮动换算就得 填写两个数量计算出浮动率就可以了
        if (this.form.storageUnitType === 'float') {
          this.handleFloatCalculate()
        }
      }
    },
    handleSelectStock(){
      this.$refs.itemSelect.showFlag = true;
      this.$refs.itemSelect.itemTypeIdRange=this.itemTypeIdRange
      this.$refs.itemSelect.getList();
    },
    handleAddProduct(){
      this.resetDialogForm();
      console.log("handleAddProduct",this.itemTypeIdRange)
      this.warehouseInfo=[]
      if(this.goodsInventoryAddForm.inventoryRange =='仓库'){

        this.form.warehouseName=this.goodsInventoryAddForm.warehouseName
        this.form.locationName=this.goodsInventoryAddForm.locationName
        this.form.areaName=this.goodsInventoryAddForm.areaName
          // this.warehouseInfo=[this.goodsInventoryAddForm.warehouseId,this.goodsInventoryAddForm.locationId,this.goodsInventoryAddForm.areaId]
      }
      if(this.goodsInventoryAddForm.inventoryRange =='物料分类'){
        this.isckDisabled=true
      }
      this.open = true;
      this.$forceUpdate()
    },
    handleDeleteProduct(row){
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除为"' + this.itemName + '"的数据项？').then(function() {
        return delPandianproduct(ids);
      }).then(() => {
        this.getProductList()
        this.$forceUpdate()
        // this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});

    },
    //提交盘点单
    submitTijiao(){
      this.$modal.confirm('是否确认提交单号为"' + this.goodsInventoryAddForm.sn + '"的盘点单？确认后无法修改','提示',{confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'}).then(() => {
        updatePandianStatus(this.goodsInventoryAddForm.id).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.visible = false;
          this.$emit('refreshDataList')
          /* localStorage.setItem("IndexRefresh", true);
           // 调用全局挂载的方法，关闭当前页
           this.$store.dispatch("tagsView/delView", this.$route)
           // this.$router.push({path: '/pandian/pandian'});
           this.$router.go(-1)*/
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //提交物料弹窗
    submitDialogForm(){
      this.$refs[ "form" ].validate(valid => {
        if (valid) {
          this.form.inventoryId=this.goodsInventoryAddForm.id
          if(this.goodsInventoryAddForm.inventoryRange == '仓库'){
            this.form.warehouseId=this.goodsInventoryAddForm.warehouseId
            this.form.warehouseCode=this.goodsInventoryAddForm.warehouseCode
            this.form.warehouseName=this.goodsInventoryAddForm.warehouseName
            this.form.locationId=this.goodsInventoryAddForm.locationId
            this.form.locationCode=this.goodsInventoryAddForm.locationCode
            this.form.locationName=this.goodsInventoryAddForm.locationName
            this.form.areaId=this.goodsInventoryAddForm.areaId
            this.form.areaCode=this.goodsInventoryAddForm.areaCode
            this.form.areaName=this.goodsInventoryAddForm.areaName
          }
          if(this.form.inventoryNum <= 0){
            this.$modal.msgWarning("盘点数量（主）必须大于0");
            return
          }
          if('Y' == this.form.enableMultiUnit){
            if(this.form.storageInventoryNum <= 0){
              this.$modal.msgWarning("盘点数量（库存）必须大于0");
              return
            }
          }
        //新添加的物料 都是盘盈的 库存主/辅 数量都是0
          addPandianproduct(this.form).then(response => {
            this.$modal.msgSuccess("物料添加成功");
            this.open = false;
            this.getProductList();
          });
        }
      })
    },
    //取消物料弹窗
    cancelDialog(){
      this.resetDialogForm();
      this.open=false
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.itemName= selection.map(item => item.itemName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 查询修改 */
    getList(pandianId) {
      //查询详情
      getPandian(pandianId).then(response => {
        this.goodsInventoryAddForm=response.data
        if(this.goodsInventoryAddForm.inventoryRange =='物料分类'){
          this.itemTypeIdRange = this.goodsInventoryAddForm.itemTypeIdRange.split(",")
        }else{
          this.itemTypeIdRange=[]
        }

      /*  this.warehouseInfo[0] = response.data.warehouseId;
        this.warehouseInfo[1] = response.data.locationId;
        this.warehouseInfo[2] = response.data.areaId;
        this.zujFlag=true
    */
        /*    console.log("goodsInventoryAddForm",this.goodsInventoryAddForm.productList)*/
        this.getWarehouseList();
        this.$forceUpdate()
        //加载物料
          this.getProductList()

      });
      this.$forceUpdate()
    },
    getProductList(){
      getProductByPId(this.goodsInventoryAddForm.id).then(response => {
        // console.log("productList",this.goodsInventoryAddForm.productList)
        console.log("response.data",response.data)
        console.log("response.data",response.data.length )
        if(response.data.length >0){
          console.log("3333333")
          this.goodsInventoryAddForm.productList=response.data
        }else {
          this.buttonIsShow =true
          this.goodsInventoryAddForm.productList=[]
        }
      });
    },

    //点击人员选择按钮
    handleUserSelect(){
      this.$refs.userSelect.showFlag = true;
    },
    //人员选择返回
    onUserSelected(row){
      this.goodsInventoryAddForm.inventoryPerson= row.nickName;
      this.goodsInventoryAddForm.inventoryPersonId= row.userId;
      this.$forceUpdate()
    },
    /** 提交按钮 */
    submitGoodsInventoryAddForm() {
      if(this.goodsInventoryAddForm.productList.length <= 0 ){
        this.$message({
          type: 'warning',
          message: '请填充物料明细，再进行保存！'
        });
        return
      }
      this.$refs["goodsInventoryAddForm"].validate(valid => {
        if (valid) {
          if (this.goodsInventoryAddForm.id != null) {
            updatePandian(this.goodsInventoryAddForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.visible = false;
              this.buttonIsShow=false
              this.$emit('refreshDataList')
           /*   //刷新列表
              localStorage.setItem("IndexRefresh", true);
              this.$store.dispatch("tagsView/delView", this.$route)
              // this.$router.push({path: '/pandian/pandian'});
              this.$router.go(-1)*/
            });
          }
          this.reset()
        }
      });


    },
    // 新增物料时 的重置
    resetDialogForm() {
      this.form = {
        inventoryId:this.goodsInventoryAddForm.id,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        warehouseId: null,
        warehouseName: null,
        warehouseCode: null,
        locationId: null,
        locationName: null,
        locationCode: null,
        areaId: null,
        areaName: null,
        areaCode: null,
        quantityOnhand:0,
        inventoryNum:null,
        batchCode:null,
        remark:null
      };
      this.resetForm("form");
      this.isflckDisabled=false;

    },
    reset() {
      this.goodsInventoryAddForm = {
        id: null,        sn: null,        warehouseId: null,        warehouseName: null,        locationId: null,
        locationName: null,        areaId: null,        areaName: null,        inventoryPersonId: null,
        inventoryPerson: null,        inventoryTime: null,        inventoryDesc: null,        status: null,
        rejectReason: null,        auditTime: null,        auditPersonId: null,        auditPersonName: null,
        createBy: null,        createTime: null,        updateBy: null,        updateTime: null , inventoryType:'静态',
        inventoryMethod:null
        ,storageUnitType:null,
        storageUnit:null,
        storageRatio:0,
        storageUnitquantity:0,
        enableMultiUnit:'N',
        storageInventoryNum:0,
        storageDiffNum:0
      };
      this.goodsInventoryAddForm.productList=[]
      this.resetForm("goodsInventoryAddForm");
      this.itemTypeIdRange=[]
    },
    // 取消按钮
    cancel() {
     /* localStorage.setItem("IndexRefresh", true);
      // 调用全局挂载的方法，关闭当前页
      this.$store.dispatch("tagsView/delView", this.$route)
      this.$router.go(-1)*/
      // 取消按钮
      this.reset()
      this.buttonIsShow= false
      this.visible = false;
      this.resetDialogForm()
      this.$emit('refreshDataList')
    },
    //商品差
    handleEdit(index,row) {
      this.$forceUpdate()
 /*     console.log('indexqqqq',index)
      console.log('差异',row.diffNum)
      console.log('盘点数',row.inventoryNum)
      console.log('库存数',row.quantityOnhand)*/

        // if( row.inventoryNum){
        // row.diffNum = parseFloat(Number(row.inventoryNum)-Number(row.quantityOnhand)).toFixed(2)
        row.diffNum = Number(row.inventoryNum) - Number(row.quantityOnhand)


        // console.log("ddddd",row.diffNum)
      // }
     /*   if(row.inventoryNum == 0){
          row.diffNum = Number(row.inventoryNum) - Number(row.quantityOnhand)
        }*/
    },
    handleFuEdit(index,row) {
      this.$forceUpdate()
   /*   console.log('indexqqqq',index)
      console.log('差异',row.storageDiffNum)
      console.log('盘点数',row.storageInventoryNum)
      console.log('辅单位库存数',row.storageUnitquantity)*/

      // if( row.inventoryNum){
      // row.diffNum = parseFloat(Number(row.inventoryNum)-Number(row.quantityOnhand)).toFixed(2)
      row.storageDiffNum = Number(row.storageInventoryNum) - Number(row.storageUnitquantity)
      // console.log("ddddd",row.diffNum)
      // }
      /*   if(row.inventoryNum == 0){
           row.diffNum = Number(row.inventoryNum) - Number(row.quantityOnhand)
         }*/
    },
    // 选择出库单
     handleSelectWarehouseEntryBatch() {

      this.getCKItemList()
     /* if (!this.goodsInventoryAddForm.warehouseId) {
        this.$message.error('请先选择仓库！')
        return
      }
      this.$refs.itemSelect.showFlag = true;*/

    },
    //物料选择弹出框
    onItemSelected(obj){
      this.form.itemId = obj.itemId;
        this.form.itemCode= obj.itemCode;
        this.form.itemName= obj.itemName;
        this.form.specification= obj.specification;
        this.form.unitOfMeasure= obj.unitOfMeasure;
        this.form.enableMultiUnit=obj.enableMultiUnit;
        this.form.storageUnitType=obj.storageUnitType;
        this.form.storageRatio=obj.storageRatio;
        this.form.storageUnit=obj.storageUnit;
 /*     最开始版本console.log("obj",obj)
      if(this.goodsInventoryAddForm.productList.length >0){
        // 看所选物料是否重复
        var commonElements = $.grep(this.goodsInventoryAddForm.productList, function(element) {
          return $.grep(obj, function(el) {
            if(el.itemId === element.itemId && el.batchCode == element.batchCode){
              return el.itemId === element.itemId;
            }
          }).length > 0;
        })

        if(commonElements.length > 0){
          this.$message.warning("物料存在重复请重新选择")
          return
        }
        this.goodsInventoryAddForm.productList=this.goodsInventoryAddForm.productList.concat(obj)
      }else{
        //第一次增加
        this.goodsInventoryAddForm.productList=obj
      }*/
    },
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj){
      console.log("handleWarehouseChanged",obj)
      const selectedNodes = this.$refs.selectck.getCheckedNodes();
      console.log("selectedNodes",selectedNodes)
      console.log('选中的名称11:',selectedNodes[0].pathLabels)
      if(obj !=null){
        this.form.warehouseId = obj[0];
        this.form.locationId = obj[1];
        this.form.areaId = obj[2];
        this.form.warehouseName=selectedNodes[0].pathLabels[0]
        this.form.locationName=selectedNodes[0].pathLabels[1]
        this.form.areaName=selectedNodes[0].pathLabels[2]
      }
    },
    getWarehouseList(){
      getTreeList().then( response =>{
        if(response.data){
          this.warehouseOptions = response.data.filter((el) =>{
            return el.warehouseCode.indexOf('VIR') == -1;
          });
        }
        // console.log("1111",this.warehouseOptions)
        this.warehouseOptions.map(w =>{
          w.children.map(l =>{
            let lstr =JSON.stringify(l.children).replace(/locationId/g,'lId').replace(/areaId/g, 'pId').replace(/areaName/g,'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g,'wId').replace(/locationId/g, 'pId').replace(/locationName/g,'pName');
          w.children =  JSON.parse(wstr);

        });
        let ostr=JSON.stringify(this.warehouseOptions).replace(/warehouseId/g,'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
        console.log('2222',JSON.parse(ostr))
      });
    },
    // 根据仓库信息获取item
    getCKItemList() {
      this.loading = true;
      this.queryParams.warehouseId= this.goodsInventoryAddForm.warehouseId
      this.queryParams.locationId=this.goodsInventoryAddForm.locationId
      this.queryParams.areaId=this.goodsInventoryAddForm.areaId
      console.log(this.queryParams)
      getListWmstock(this.queryParams).then(response => {
        if(response.data.length >0){
          this.goodsInventoryAddForm.productList = response.data;
          this.goodsInventoryAddForm.productList.some(item => { item.inventoryNum = item.quantityOnhand})
          // this.total = response.total;
          this.loading = false;
        } else {
          this.$message({
            type: 'warning',
            message: '该仓库中未获取到物料，请检查！'
          });
        }
      });
    },
  },
  //最初版本删除 废弃
  deleteProduct(index,row){
    if(this.goodsInventoryAddForm.id){

      this.$confirm('确定要删除物料 “'+row.itemCode + row.itemName +'" 的数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProByPidItemId(this.goodsInventoryAddForm.id,row.itemId)
        this.goodsInventoryAddForm.productList.splice(index, 1)
        row.diffNum=0
        row.inventoryNum=0
        row.remark=''
        console.log("del hou",this.goodsInventoryAddForm.productList)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        // this.$router.go(0)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    }else{
      this.$message.warning("无法删除，请联系管理员")
    }

  }


}
</script>



